﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MQTTService;

namespace MQTTClient
{
	public partial class Form1 : Form
	{

		public Form1()
		{
			InitializeComponent();
		}

		private delegate void myUICallBack(string myStr, TextBox ctl);
		MQTTClients clients = new MQTTClients();

		private void myUI(string myStr, TextBox ctl)
		{
			if (base.InvokeRequired)
			{
				myUICallBack method = new myUICallBack(this.myUI);
				base.Invoke(method, new object[]
				{
					myStr,
					ctl
				});
			}
			else
			{
				ctl.AppendText(myStr + Environment.NewLine);
			}
		}
		private void Form1_Load(object sender, EventArgs e)
		{
			base.AcceptButton = this.ConnectButton;
			this.QosComboBox.SelectedIndex = 1;
			clients.ClientConnecteds += new MQTTClients.ClientConnected(ClientConnected);
			clients.ClientDisconnecteds += new MQTTClients.ClientDisconnected(ClientDisconnected);
			clients.MessageReceiveds += new MQTTClients.MessageReceived(MessageReceived);
		}

		private void Form1_Closing(object sender, FormClosingEventArgs e)
		{
            try
            {
				if (clients != null)
				{
					clients.UnInitClient();
				}
			}
            catch (Exception ex)
            {
            }
			
			System.Diagnostics.Process.GetCurrentProcess().Kill();
		}

		private void ConnectButton_Click(object sender, EventArgs e)
		{
			int brokerPort;
			if (this.HostTextBox.Text.Length == 0)
			{
				this.label4.Text = "Invild host";
			}
			else if (!int.TryParse(this.PortTextBox.Text, out brokerPort))
			{
				this.label4.Text = "Invild port";
			}
			else
			{
                if (clients.InitClient(HostTextBox.Text,Convert.ToInt32(PortTextBox.Text)))
                {
					base.AcceptButton = this.PublishButton;
					this.label4.Text = "";
					this.MessageTextBox.Clear();
					this.SubscribeButton.Enabled = true;
					this.PublishButton.Enabled = true;
					this.UnsubscribeButton.Enabled = true;
					this.DisconnectButton.Enabled = true;
					this.ConnectButton.Enabled = false;
					this.HostTextBox.Enabled = false;
					this.PortTextBox.Enabled = false;
                }
			}
		}

		private void DisconnectButton_Click(object sender, EventArgs e)
		{
			clients.UnInitClient();
			this.SubscribeButton.Enabled = false;
			this.PublishButton.Enabled = false;
			this.UnsubscribeButton.Enabled = false;
			this.DisconnectButton.Enabled = false;
			this.ConnectButton.Enabled = true;
			this.HostTextBox.Enabled = true;
			this.PortTextBox.Enabled = true;
			this.SubListBox.Items.Clear();
		}

        [Obsolete]
        private void SubscribeButton_Click(object sender, EventArgs e)
		{
			string str = SubTopicTextBox.Text;
			List<TopicsM> ms = new List<TopicsM>();
			ms.Add(new TopicsM() { Topics=str,QOSEnum=QOSEnum.AtMostOnce,IsCheck = true });
			clients.SubscribeTopics(ms);
			this.SubListBox.Items.Add(this.SubTopicTextBox.Text);
		}

        [Obsolete]
        private void PublishButton_Click(object sender, EventArgs e)
		{
			this.Invoke((EventHandler)delegate
			{
				if (this.PubMessageTextBox.Text.Length == 0)
				{
					this.label4.Text = "No message to send";
				}
				else if (this.PubTopicTextBox.Text.Length == 0)
				{
					this.label4.Text = "Publish topic can't be empty";
				}
				else if (this.PubTopicTextBox.Text.IndexOf('#') != -1 || this.PubTopicTextBox.Text.IndexOf('+') != -1)
				{
					this.label4.Text = "Publish topic can't include wildcard(# , +)";
				}else
                {
					this.label4.Text = "";
					TopicsM model = new TopicsM()
					{
						Topics = PubTopicTextBox.Text,
						QOSEnum = QOSEnum.AtMostOnce,
						Describe = PubMessageTextBox.Text,
						IsCheck = true
					};
					clients.Publish_Message(model);

                }
            });
		}

		private void ClearButton_Click(object sender, EventArgs e)
		{
			this.MessageTextBox.Clear();
		}

        [Obsolete]
        private void UnsubscribeButton_Click(object sender, EventArgs e)
		{
			if (this.SubListBox.SelectedItem == null)
			{
				this.label4.Text = "Select topic to unscribe";
			}
			else
			{
				this.label4.Text = "";
				clients.UnSubscribeTopics((new string[]
				{
					this.SubListBox.SelectedItem.ToString()
				}).ToList());
				this.SubListBox.Items.Remove(this.SubListBox.SelectedItem);
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && this.components != null)
			{
				this.components.Dispose();
			}
			base.Dispose(disposing);
		}

		private void ClientConnected(bool ClientId)
		{
			//this.Invoke((EventHandler)delegate
			//{
			//	if (string.IsNullOrEmpty(textBox1.Text))
			//	{
			//		textBox1.Text += $@"客户端>{ClientId}";
			//	}
			//	else
			//	{
			//		textBox1.Text += $@"{Environment.NewLine}客户端>{ClientId}";
			//	}
			//});

		}
		private void ClientDisconnected(bool IsDisConn)
		{

			//this.Invoke((EventHandler)delegate
			//{
			//	//if (string.IsNullOrEmpty(textBox1.Text))
			//	//{
			//	//	textBox1.Text += $@"客户端>{ClientId}>>已断线";
			//	//}
			//	//else
			//	//{
			//	//	textBox1.Text += $@"{Environment.NewLine}客户端>{ClientId}>>已断线";
			//	//}
			//});
		}
		private void MessageReceived(string ClientId, string Topic, string Payload, string QualityOfServiceLevel, bool Retain)
		{
			this.Invoke((EventHandler)delegate
			{
				if (string.IsNullOrEmpty(MessageTextBox.Text))
				{
					MessageTextBox.Text += $@"接收到>主题>>>{Topic}》》》消息体>>>{Payload}";
				}
				else
				{
					MessageTextBox.Text += $@"{Environment.NewLine}接收到>主题>>>{Topic}》》》消息体>>>{Payload}";
				}
			});
		}
	}
}
